package com.atguigu.daijia.rules.config;

import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.builder.KieModule;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DroolsConfig {
    // 制定规则文件的路径
    private static final String RULES_CUSTOMER_RULES_DRL = "rules/FeeRule.drl";

    @Bean
    public KieContainer kieContainer() {
        //KieServices是Drools规则引擎的核心服务类，用于创建和管理KieContainer、KieFileSystem、KieModule等对象
        KieServices kieServices = KieServices.Factory.get();

        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();
        kieFileSystem.write(ResourceFactory.newClassPathResource(RULES_CUSTOMER_RULES_DRL));
        //加载任意路径的规则文件
//        kieFileSystem.write(ResourceFactory.newFileResource(RULES_CUSTOMER_RULES_DRL));

        //KieBuilder用于编译规则文件。buildAll()方法会编译所有规则文件
        KieBuilder kb = kieServices.newKieBuilder(kieFileSystem);
        kb.buildAll();

        //KieModule代表编译后的规则模块。getReleaseId()方法返回模块的发布ID，然后使用这个ID创建KieContainer
        KieModule kieModule = kb.getKieModule();
        KieContainer kieContainer = kieServices.newKieContainer(kieModule.getReleaseId());
        return kieContainer;
    }
}